'use strict';

const Service = require('egg').Service;

class TagService extends Service {
  // 获取标签列表
  async getList(options = {}) {
    const { Op } = this.app.Sequelize;
    const { page = 1, pageSize = 20, type, keyword } = options;

    const where = {};

    // 类型筛选
    if (type) {
      where.type = type;
    }

    // 关键词搜索
    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { description: { [Op.like]: `%${keyword}%` } },
      ];
    }

    const result = await this.ctx.model.Tag.findAndCountAll({
      where,
      order: [['type', 'ASC'], ['sort_order', 'ASC'], ['created_at', 'DESC']],
      limit: pageSize,
      offset: (page - 1) * pageSize,
    });

    return {
      list: result.rows,
      total: result.count,
      page,
      pageSize,
    };
  }

  // 获取所有启用的标签（用于下拉选择）
  async getAllActive() {
    return await this.ctx.model.Tag.findAll({
      where: { is_active: true },
      order: [['type', 'ASC'], ['sort_order', 'ASC']],
    });
  }

  // 根据类型获取标签
  async getByType(type) {
    return await this.ctx.model.Tag.findAll({
      where: { 
        type,
        is_active: true 
      },
      order: [['sort_order', 'ASC']],
    });
  }

  // 获取标签详情
  async getById(id) {
    const tag = await this.ctx.model.Tag.findByPk(id);
    if (!tag) {
      throw new Error('标签不存在');
    }
    return tag;
  }

  // 创建标签
  async create(data) {
    const { name, type, color, description, sort_order = 1, is_active = true } = data;

    // 检查标签名称是否已存在
    const existingTag = await this.ctx.model.Tag.findOne({
      where: { name, type }
    });

    if (existingTag) {
      throw new Error('该类型下已存在同名标签');
    }

    return await this.ctx.model.Tag.create({
      name,
      type,
      color,
      description,
      sort_order,
      is_active,
    });
  }

  // 更新标签
  async update(id, data) {
    const tag = await this.getById(id);
    
    const { name, type, color, description, sort_order, is_active } = data;

    // 如果修改了名称或类型，检查是否重复
    if ((name && name !== tag.name) || (type && type !== tag.type)) {
      const existingTag = await this.ctx.model.Tag.findOne({
        where: { 
          name: name || tag.name, 
          type: type || tag.type,
          id: { [this.app.Sequelize.Op.ne]: id }
        }
      });

      if (existingTag) {
        throw new Error('该类型下已存在同名标签');
      }
    }

    await tag.update({
      name: name || tag.name,
      type: type || tag.type,
      color: color || tag.color,
      description: description !== undefined ? description : tag.description,
      sort_order: sort_order !== undefined ? sort_order : tag.sort_order,
      is_active: is_active !== undefined ? is_active : tag.is_active,
    });

    return tag;
  }

  // 删除标签
  async delete(id) {
    const tag = await this.getById(id);

    // 检查是否有衣服使用了这个标签
    const clothingCount = await this.ctx.model.ClothingTag.count({
      where: { tag_id: id }
    });

    if (clothingCount > 0) {
      throw new Error(`该标签正在被 ${clothingCount} 件衣服使用，无法删除`);
    }

    await tag.destroy();
    return true;
  }

  // 批量创建默认标签
  async createDefaults() {
    const defaultTags = [
      // 风格标签
      { name: '休闲', type: 'style', color: '#409EFF', description: '休闲风格', sort_order: 1 },
      { name: '正式', type: 'style', color: '#67C23A', description: '正式风格', sort_order: 2 },
      { name: '商务', type: 'style', color: '#E6A23C', description: '商务风格', sort_order: 3 },
      { name: '运动', type: 'style', color: '#F56C6C', description: '运动风格', sort_order: 4 },
      { name: '派对', type: 'style', color: '#909399', description: '派对风格', sort_order: 5 },
      
      // 季节标签
      { name: '春季', type: 'season', color: '#67C23A', description: '春季服装', sort_order: 1 },
      { name: '夏季', type: 'season', color: '#F56C6C', description: '夏季服装', sort_order: 2 },
      { name: '秋季', type: 'season', color: '#E6A23C', description: '秋季服装', sort_order: 3 },
      { name: '冬季', type: 'season', color: '#909399', description: '冬季服装', sort_order: 4 },
      
      // 场合标签
      { name: '工作', type: 'occasion', color: '#409EFF', description: '工作场合', sort_order: 1 },
      { name: '约会', type: 'occasion', color: '#F56C6C', description: '约会场合', sort_order: 2 },
      { name: '聚会', type: 'occasion', color: '#E6A23C', description: '聚会场合', sort_order: 3 },
      { name: '旅行', type: 'occasion', color: '#67C23A', description: '旅行场合', sort_order: 4 },
    ];

    const createdTags = [];
    for (const tagData of defaultTags) {
      try {
        const existingTag = await this.ctx.model.Tag.findOne({
          where: { name: tagData.name, type: tagData.type }
        });
        
        if (!existingTag) {
          const tag = await this.ctx.model.Tag.create(tagData);
          createdTags.push(tag);
        }
      } catch (error) {
        console.error(`创建默认标签失败: ${tagData.name}`, error);
      }
    }

    return createdTags;
  }
}

module.exports = TagService;
